﻿using System;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Abp.Auditing;
using Abp.Domain.Repositories;
using Abp.Runtime.Caching;
using Abp.Timing;
using SimpleCmsWithAbp.Net.MimeTypes;
using SimpleCmsWithAbp.VerifyCodes.Dto;

namespace SimpleCmsWithAbp.VerifyCodes
{
    public class VerifyCodeAppService:SimpleCmsWithAbpAppServiceBase,IVerifyCodeAppService
    {
        private readonly IRepository<VerifyCode, long> _repository;

        public VerifyCodeAppService(IRepository<VerifyCode, long> repository)
        {
            _repository = repository;
        }

        public async Task<GetVerifyCodeOutput> Get()
        {
            var v = new VerifyCodeCore();
            var code = v.CreateVerifyCode();                //取随机码
            v.Padding = 10;
            var bytes = v.CreateImage(code);
            var image = $"data:{MimeTypeNames.ImageJpeg};base64,{Convert.ToBase64String(bytes)}";
            var verifyCode = new VerifyCode()
            {
                Md5Key = GetMd5Key(image),
                Code = code,
                Expired = Clock.Now.AddMinutes(10)
            };
            await _repository.InsertAsync(verifyCode);
            var output = new GetVerifyCodeOutput()
            {
                Image = image
            };
            return output;
        }

        private static string GetMd5Key(string input)
        {
            var md5 = new MD5CryptoServiceProvider();
            var inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
            var hashBytes = md5.ComputeHash(inputBytes);

            // Convert the byte array to hexadecimal string
            var sb = new StringBuilder();
            foreach (var t in hashBytes)
            {
                sb.Append(t.ToString("X2"));
            }
            return sb.ToString();
        }
    }
}